package org.example.framework.register;

import cn.hutool.core.io.FileUtil;
import cn.lingyangwl.framework.tool.core.file.FileUtils;
import org.example.framework.ServerUrl;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shenguangyang
 */
public class RemoteRegister {
    private static final Map<String, List<ServerUrl>> map = new HashMap<>();
    private static final String SHARD_FILE_NAME = "remote-shared";

    public static void register(String interfaceName, ServerUrl serverUrl) {
        List<ServerUrl> serverUrls = map.get(interfaceName);
        if (serverUrls == null) {
            synchronized (RemoteRegister.class) {
                FileUtils.deleteFile(SHARD_FILE_NAME);
                serverUrls = map.computeIfAbsent(interfaceName, k -> new ArrayList<>());
            }
        }
        serverUrls.add(serverUrl);

        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream;
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(serverUrls);
            byte[] bytes = byteArrayOutputStream.toByteArray();

            FileUtil.writeBytes(bytes, new File(SHARD_FILE_NAME));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static List<ServerUrl> get(String interfaceName) {
        try {
            List<ServerUrl> serverUrls = map.get(interfaceName);
            if (serverUrls == null) {
                byte[] bytes = FileUtil.readBytes(new File(SHARD_FILE_NAME));
                serverUrls = (List<ServerUrl>) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
                map.put(interfaceName, serverUrls);
            }
            return map.get(interfaceName);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
